package com.winit.openapi.tms.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.utils.Collections3;
import com.winit.openapi.constants.EnumConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.pms.spi.v2.instance.pscInstance.ProductInstanceService;
import com.winit.pms.spi.v2.instance.pscInstance.command.GetTransportTypeCommand;
import com.winit.pms.spi.winit.WinitProductItemService;
import com.winit.pms.spi.winit.WinitProductService;
import com.winit.pms.spi.winit.WinitRuleService;
import com.winit.pms.spi.winit.command.WinitProductQueryCommand;
import com.winit.pms.spi.winit.vo.WinitProduct;
import com.winit.tms.spi.common.ProductCategoryConstant;
import com.winit.tms.spi.common.TMSConstants;
import com.winit.tms.spi.common.vo.DeliveryWayVo;
import com.winit.tms.spi.logistics.LogisticsPlanService;
import com.winit.tms.spi.logistics.command.LogisticsPlanQueryCommand;
import com.winit.tms.spi.logistics.vo.LogisticsPlanVo;

/**
 * 物流计划
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * hou 	1.0  		2015-11-14 	Created
 * 
 * </pre>
 * @since 1.
 */

@Controller
@RequestMapping(value = "/tms/logisticsPlan")
public class LogisticsPlanController extends BaseController {

    private static final Logger     logger = LoggerFactory.getLogger(LogisticsPlanController.class);

    @Resource
    private LogisticsPlanService    logisticsPlanService;
    @Resource
    private WinitRuleService        winitRuleService;
    @Resource
    private WinitProductService     winitProductService;
    @Resource
    private WinitProductItemService winitProductItemService;
    @Resource
    private ProductInstanceService  productInstanceService;

    /**
     * 查询物流计划
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryLogisticsPlan")
    public String queryLogisticsPlan(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            String productCode = json.getString("productCode");

            String delivery = "";
            String planType = TMSConstants.KUAIDI_TYPE;
            String productType = json.getString("winitProductType");
            Date deliveryDeadline = json.getDate("deliveryDeadline");
            if (StringUtils.isNotEmpty(productType)
                && !ProductCategoryConstant.ProductCategory.CATEGORY_GTP.getCode().equals(productType)) {
                GetTransportTypeCommand typeCommand = new GetTransportTypeCommand();
                typeCommand.setProductCode(productCode);
                DeliveryWayVo wayVo = productInstanceService.getTransportTypeByCode(typeCommand);
                if (wayVo != null) {
                    delivery = wayVo.getDeliveryWay();
                    planType = wayVo.getTransportType();
                }
            } else {
                WinitProductQueryCommand suCommand = new WinitProductQueryCommand();
                suCommand.setCode(productCode);
                try {
                    List<WinitProduct> serviceList = winitProductItemService.queryServiceItemAllByProductIdOrCode(suCommand);
                    // 找出服务里的运输方式 空运:C0301|C030102 海运:C0302|C030202 快递:C0303
                    if (Collections3.isNotEmpty(serviceList)) {
                        for (WinitProduct serviceUnit : serviceList) {
                            if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_AIR.getCode()
                                .equals(serviceUnit.getServiceCatalogCode())
                                || EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_AIR_V2.getCode()
                                    .equals(serviceUnit.getServiceCatalogCode())) {
                                planType = TMSConstants.KONGYUN_TYPE;
                                break;
                            } else if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_SEA.getCode()
                                .equals(serviceUnit.getServiceCatalogCode())
                                       || EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_SEA_V2.getCode()
                                           .equals(serviceUnit.getServiceCatalogCode())) {
                                planType = TMSConstants.HAIYUN_TYPE;
                                break;
                            } else if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_EXPRESS.getCode()
                                .equals(serviceUnit.getServiceCatalogCode())) {
                                planType = TMSConstants.KUAIDI_TYPE;
                                break;
                            }
                        }
                    }
                    WinitProductQueryCommand querycommand = new WinitProductQueryCommand();
                    querycommand.setCode(productCode);
                    WinitProduct winitProduct = winitProductService.queryProduct(querycommand);
                    delivery = winitProduct.getAssemblyType();
                } catch (Exception e) {
                    logger.error("查询服务分类失败", e);
                }
            }
            String inspectionWarehouseCode = json.getString("inspectionWarehouseCode");
            String purposeWarehouseCode = json.getString("purposeWarehouseCode");

            LogisticsPlanQueryCommand command = new LogisticsPlanQueryCommand();
            command.setDelivery(delivery);
            command.setPlanType(planType.toLowerCase());
            command.setInspectionWarehouseCode(inspectionWarehouseCode);
            command.setPurposeWarehouseCode(purposeWarehouseCode);
            command.setEarliestReservationDate(null == json.getDate("earliestReservationDate") ? null : json.getDate("earliestReservationDate"));
            command.setDeliveryDeadline(deliveryDeadline);
            List<LogisticsPlanVo> planVos = logisticsPlanService.queryLogisticsPlan(command);

            Map<Object, Object> data = new HashMap<Object, Object>();
            data.put("planVos", planVos);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/getLogisticsPlanList")
    public String getLogisticsPlanList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            String delivery = json.getString("delivery");
            String inspectionWarehouseCode = json.getString("inspectionWarehouseCode");
            String purposeWarehouseCode = json.getString("purposeWarehouseCode");
            LogisticsPlanQueryCommand command = new LogisticsPlanQueryCommand();
            command.setDelivery(delivery);
            command.setInspectionWarehouseCode(inspectionWarehouseCode);
            command.setPurposeWarehouseCode(purposeWarehouseCode);
            command.setEndPlaceorderDate(null == json.getDate("endPlaceorderDate") ? null : json.getDate("endPlaceorderDate"));
            List<LogisticsPlanVo> planVos = logisticsPlanService.getLogisticsPlanList(command);
            Map<Object, Object> data = new HashMap<Object, Object>();
            data.put("planVos", planVos);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
}
